<template>
  <div>
    <button @click="startRecording" :disabled="recording">开始录音</button>
    <button @click="stopRecording" :disabled="!recording">停止录音</button>
    <button @click="uploadRecording" :disabled="!audioData">上传录音</button>
    <audio ref="audio" controls></audio>
  </div>
</template>

<script>
/** vue2版本 */

export default {
  name: 'vue2AudioView',
  data() {
    return {
      recording: false,
      mediaStream: null,
      mediaRecorder: null,
      audioChunks: [],
      audioData: null
    }
  },
  methods: {
    async startRecording() {
      try {
        this.mediaStream = await navigator.mediaDevices.getUserMedia({
          audio: true
        })
        this.mediaRecorder = new MediaRecorder(this.mediaStream)
        this.mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            this.audioChunks.push(event.data)
          }
        }
        this.mediaRecorder.start()
        this.recording = true
      } catch (error) {
        console.error('getUserMedia error:', error)
      }
    },
    stopRecording() {
      if (this.mediaRecorder) {
        this.mediaRecorder.stop()
        this.mediaStream.getTracks().forEach((track) => track.stop())
        this.recording = false
        this.playAudio()
      }
    },
    playAudio() {
      const audioBlob = new Blob(this.audioChunks, { type: 'audio/webm' })
      const audioUrl = URL.createObjectURL(audioBlob)
      this.$refs.audio.src = audioUrl
      console.log(audioBlob, 111)
      console.log(this.$refs.audio, 3333)
      this.audioData = audioBlob
    },
    async uploadRecording() {
      if (this.audioData) {
        const formData = new FormData()
        formData.append('audio', this.audioData)

        try {
          // 使用 Axios 发送录音文件到后端
          // const response = await xxx("YOUR_BACKEND_API_URL", formData);
          // console.log("文件上传成功:", response.data);
        } catch (error) {
          console.error('文件上传失败:', error)
        }
      }
    }
  }
}
</script>

<style>
/* Add your styles here */
</style>
